import json
from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session as SessionStore
from flask import session
from sqlalchemy.orm import backref


app = Flask(__name__, template_folder="templates", static_folder="static")

# 把SQLAlchemy组件注册到项目中
db = SQLAlchemy()

# 实例化session存储类
session_store = SessionStore()

# 把session通过SQLAlchemy保存到mysql中
settings = {
    # 设置SECRET_KEY
    "SECRET_KEY": "*Kjfladjflakdsfuwer*(^&!(#^(*!)))1a2wqe1233r21adf24",
    # 连接数据库连接url
    "SQLALCHEMY_DATABASE_URI": "mysql://zhangyz:123456@10.4.7.13:3306/school?charset=utf8mb4",
    # 动态追踪修改设置，如未设置只会提示警告
    "SQLALCHEMY_TRACK_MODIFICATIONS": True,
    # 查询时会显示原始SQL语句
    "SQLALCHEMY_ECHO": True,
    "SESSION_TYPE": "sqlalchemy", # session类型为sqlalchemy
    "SESSION_SQLALCHEMY": db, # SQLAlchemy的数据库连接对象
    "SESSION_SQLALCHEMY_TABLE": "sessions", # session要保存的表名称
    "SESSION_PERMANENT": True, # 如果设置为True，则关闭浏览器session就失效
    "SESSION_USE_SIGNER": True, # 是否对发送到浏览器上session的cookie值进行添加签名，防止串改
    "SESSION_KEY_PREFIX": "session:" # session数据表中sessionID的前缀，默认就是 session:
}
app.config.update(settings)


# sqlalchemy初始化
db.init_app(app)
# 务必保证在数据库配置初始化以后才进行session存储类的初始化
session_store.init_app(app)


@app.route("/test01")
def test01():
    return "ok"

@app.route("/test02")
def test02():
    session["uname"] = "zhangyz"
    session["age"] = 29
    return "ok"

@app.route("/get_session")
def get_session():
    print(session.get("uname"))
    print(session.get("age"))
    return "ok"

@app.route("/del_session")
def del_session():
    print(session.pop("uname"))
    print(session.pop("age"))
    return "ok"


if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(host='0.0.0.0', port=5000, debug=True)